package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
)

func sayHello(w http.ResponseWriter, r *http.Request) {

	r.ParseForm() // 解析参数，默认是不会解析的
	fmt.Println(r.Form)
	fmt.Printf("请求的路径path %v", r.URL.Path)
}

func Login(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		r.ParseForm()
		values := r.Form
		username := values.Get("username")
		password := values.Get("password")
		if password != "" {
			w.Write([]byte(username))
		}

	} else {
		w.Write([]byte("请使用GET请求"))
		return
	}
}

func UploadFile(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	file, handler, err := r.FormFile("file")
	if err != nil {
		return
	}
	defer file.Close()
	//通过os将文件写入指定的磁盘
	f, err := os.OpenFile("d:/GODEMO/"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)

	if err != nil {
		return
	}

	defer f.Close()

	io.Copy(f, file)

}

func main() {

	http.HandleFunc("/test", sayHello)
	http.HandleFunc("/login", Login)

	http.HandleFunc("/uploadFile", UploadFile)

	err := http.ListenAndServe(":8090", nil)
	if err != nil {
		fmt.Printf("service start failed %v", err)
		return
	}

}
